"""
This is a utility for generating amchart setting xml fragments.

Look for environment entries starting PREFIX+"."
If the suffix contains no dot then generate xml fragment <suffix>value</suffix>.
"""

from whiff.middleware import misc

class xmlElement(misc.utility):
    def __init__(self, prefix):
        self.prefix = prefix
    def __call__(self, env, start_response):
        prefix = self.param_value(self.prefix, env)
        fragment = matches(prefix, env)
        return self.deliver_page(fragment, env, start_response)

def matches(prefix, env):
    prefix = prefix+"."
    L = []
    submatches = {}
    ks = env.keys()
    lenprefix = len(prefix)
    for k in ks:
        if k.startswith(prefix):
            suffix = k[lenprefix:]
            if "." in suffix:
                submatchPrefix = suffix.split(".")[0]
                submatch = prefix+submatchPrefix
                submatches[submatch] = submatchPrefix
            else:
                value = env[k]
                fragment = "<%s>%s</%s>" % (suffix, value, suffix)
                L.append(fragment)
    # recursively handle submatches
    for (submatch,tag) in submatches.items():
        submatchfragment = matches(submatch, env).replace("\n", "\n ")
        fragment = "<%s>\n %s\n</%s>" % (tag, submatchfragment, tag)
        L.append(fragment)
    return "\n".join(L)

__middleware__ = xmlElement

def test():
    env = {
        "amchart.settings.pie.angle": 45,
        "amchart.settings.pie.height": 10,
        "amchart.settings.font": "courier",
        }
    app = xmlElement("amchart")
    response = app(env, misc.ignore)
    text = "".join(response)
    print "test result is"
    print text
                                                          
if __name__=="__main__":
    test()
